package team.lourd.network.system.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;


/** 
* @Description: 邮件发送服务
* @Author: Lourd 
* @Date: 2019/1/17 
*/
@Component
public class EmailService {

    @Autowired
    private SimpleMailMessage template;

    @Autowired
    private JavaMailSender emailSender;

    /** 
    * @Description: 发送简单邮件 
    * @Param: [to, subject, text] 
    * @return: void 
    * @Author: Lourd
    * @Date: 2019/1/17 
    */
    public void sendSimpleMessage(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        emailSender.send(message);
    }

    /** 
    * @Description: 发送带有附件的Mail
    * @Param: [to, subject, text, pathToAttachment] 
    * @return: void 
    * @Author: Lourd
    * @Date: 2019/1/17 
    */
    public void sendMessageWithAttachment(String to, String subject, String text, String pathToAttachment) throws MessagingException {
        MimeMessage message = emailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);

        FileSystemResource file
                = new FileSystemResource(new File(pathToAttachment));
        helper.addAttachment("Invoice", file);

        emailSender.send(message);
    }
}
